/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Project;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.bean.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;

/**
 *
 * @author Luke Nomeland
 */
@Named
@SessionScoped
public class UserBean implements Serializable {

    private static String userName = "";
    private String password;
    private String firstName = "", lastName = "", email = "", email2 = "";
    private boolean userNameError = false;
    private boolean userNotFound = false;
    private boolean passwordIncorrect = false;
    private boolean loggedIn = false;
    @Resource(name = "jdbc/mydb")
    private DataSource ds;

    /*
     * @param
     * @return 
     * this function is an empty constructor for userBean
     */
    public UserBean() {
    }


    /*
     * @param 
     * @return userbean.username
     * this function returns the current username according to whats in the username field
     */
    public String getUserName() {
        return UserBean.userName;
    }
    /*
     * @param String quizNme
     * @return 
     * this function sets the username taken in into the userbeans.username field
     */

    public void setUserName(String userName) {
        UserBean.userName = userName;
    }
    /*
     * @param 
     * @return String password
     * this function will return the users password
     */

    public String getPassword() {
        return this.password;
    }
    /*
     * @param String password
     * @return 
     * this function sets the password for the current user
     */

    public void setPassword(String password) {
        this.password = password;
    }
    /*
     * @param 
     * @return String firstName
     * this function sets the password for the current user
     */

    public String getFirstName() {
        return firstName;
    }
    /*
     * @param String firstName
     * @return 
     * this function sets the password for the current user
     */

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    /*
     * @param
     * @return String lastName
     * this function sets the password for the current user
     */

    public String getLastName() {
        return lastName;
    }
    /*
     * @param String lastName
     * @return 
     * this function sets the password for the current user
     */

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    /*
     * @param 
     * @return String email
     * this function sets the password for the current user
     */

    public String getEmail() {
        return email;
    }
    /*
     * @param String email
     * @return 
     * this function sets the password for the current user
     */

    public void setEmail(String email) {
        this.email = email;
    }

    /*
     * @param 
     * @return String email
     * this function sets the password for the current user
     */

    public String getEmail2() {
        return email2;
    }
    /*
     * @param String email
     * @return 
     * this function sets the password for the current user
     */

    public void setEmail2(String email) {
        this.email2 = email;
    }
    /*
     * @param 
     * @return boolean userNameError
     * this function will return a boolean value used to display an error message
     */

    public boolean isUserNameError() {
        return userNameError;
    }
    /*
     * @param 
     * @return boolean userNotFound
     * this function will return a boolean value used to display an error message
     */

    public boolean isUserNotFound() {
        return userNotFound;
    }
    /*
     * @param 
     * @return boolean passwordIncorrect
     * this function will return a boolean value used to display an error message
     */

    public boolean isPasswordIncorrect() {
        return passwordIncorrect;
    }

    /*
     * @param 
     * @return boolean true : false
     * this function will return true if the user is logged in or false if the user is not logged in
     */

    public boolean isLoggedIn() {
        return this.loggedIn;
    }
    /*
     * @param 
     * @return boolean correctPage
     * this function checks to make sure passwords are equal,
     * if they are not equal an error message is displayed
     * next it gets a resultSet that checks to see if the userName already exists
     * else the user is properly registered 
     */
    public String registerUser() throws SQLException {

        ResultSet rs = isExist(userName);

        if (rs.next()) {
            userNameError = true;
            return "registration";
        } else {
            Connection conn = ds.getConnection();
            try {
                Statement stmt = conn.createStatement();
                stmt.executeUpdate("INSERT INTO \"USER\"(USERNAME,PASSWORD,EMAIL,FIRSTNAME,LASTNAME) VALUES('" + userName + "','" + password + "','" + email + "','" + firstName + "','" + lastName + "')");
            } finally {
                conn.close();
            }
            userNotFound = false;
            userNameError = false;
            loggedIn = true;
            return "home";
        }
    }
    /*
     * @param 
     * @return correct page
     * this function makes two result sets, if the first
     * result set has any results in it the user will properly be logged in
     * if the next result set has any hits the user entered the wrong password
     * otherwise the username is not registerd
     */

    public String loginUser() throws SQLException {
        ResultSet rs = isExist(userName, password);
        ResultSet rsUser = isExist(userName);


        if (rs.next()) {
            passwordIncorrect = false;
            userNotFound = false;
            loggedIn = true;
            return "home";
        } else if (rsUser.next()) {
            passwordIncorrect = true;
            return "login";
        } else {
            userNotFound = true;
            return "login";
        }
    }
    
    public String logoutUser() {
        loggedIn = false;
        firstName = "";
        lastName = "";
        userName = "";
        password = "";
        email = "";
        email2 = "";
        return "logoutConfirmation";
    }
    

    /*
     * @param String usr
     * @return ResultSet result
     * this function will open a connection and select all users with the current Username if there 
     * are any hits it will return that
     */

    public ResultSet isExist(String usr) throws SQLException {
        Connection conn = ds.getConnection();
        try {
            Statement stmt = conn.createStatement();
            ResultSet result = stmt.executeQuery("SELECT * FROM \"USER\" where USERNAME='" + usr + "'");
            return result;
        } finally {
            conn.close();
        }
    }
    /*
     * @param String usr
     * @return ResultSet result
     * this function will open a connection and select all users with the current Username AND PASSWORD if there 
     * are any hits it will return that
     */

    public ResultSet isExist(String usr, String psswrd) throws SQLException {
        Connection conn = ds.getConnection();
        try {
            Statement stmt = conn.createStatement();
            ResultSet result = stmt.executeQuery("SELECT * FROM \"USER\" where USERNAME='" + usr + "' and PASSWORD='" + psswrd + "'");
            return result;
        } finally {
            conn.close();
        }
    }
    
    public void addWatch(int listingId) throws SQLException{
        Connection conn = ds.getConnection();
        try {
            Statement stmt = conn.createStatement();
            stmt.executeUpdate("INSERT INTO \"WATCHED\"(USERNAME,LISTINGID) VALUES('" + userName + "','" + listingId + "')");
        } finally {
            conn.close();
        }
    }
    public ResultSet getWatch() throws SQLException{
        Connection conn = ds.getConnection();
        try {
            Statement stmt = conn.createStatement();
            ResultSet result = stmt.executeQuery("SELECT * FROM \"WATCHED\" where USERNAME='" + userName + "'");
            return result;
        } finally {
            conn.close();
        }
    }

    public void removeWatch(int listingId) throws SQLException{
        Connection conn = ds.getConnection();
        try {
            Statement stmt = conn.createStatement();
            stmt.executeQuery("DELETE FROM \"WATCHED\" where listingId='" + listingId + "' AND USERNAME= '" + userName + "'");
        } finally {
            conn.close();
        }
    }
    
    
    /*
     * @param: make, model, year, mileage, price, color, and/or description 
     *         along with the ID of the carthe user wishes to update. 
     * @return: none
     * Function used to update a user's car listing. Only parameters that are not null will modify the listing.
     */
    
    public void updateListing(int ID, String make, String model, int year, int price, int miles, 
            String color, String description) throws SQLException{
        //build update string
        String listUpdate = "UPDATE car SET";
        if(make != null){
            listUpdate.concat("make ='" + make + "' WHERE carID = '" + ID + "'," );
        }
        if(model!= null){
            listUpdate.concat("model = '"+ model +"' WHERE  carID = '" + ID + "',");
        }
        if(year != -1){
            listUpdate.concat("year = '"+ year +"' WHERE carID = '" + ID + "',");
        } 
        if(price != -1){
            listUpdate.concat("price = '"+ price +"' WHERE carID = '" + ID + "',");
        }   
        if(miles != -1){
            listUpdate.concat("miles = '"+ miles +"'WHERE carID = '"+ ID +"',");
        }
        if(color != null){
            listUpdate.concat("color = '"+ color +"' WHERE carID = '" + ID + "',");
        }   
        if(description != null){
            listUpdate.concat("description = '"+ description +"' WHERE carID = '" + ID + "',");
        }   
        
        //update car table
        Connection connection = ds.getConnection();
        try{
            Statement statement = connection.createStatement();
            statement.executeUpdate(listUpdate);
        }
        finally{
            connection.close();
        }
    }
}